package com.web.servlet;

import com.bean.User;
import com.dao.UserDao;
import com.dao.impl.UserDaoImpl;
import com.web.common.exception.DataAccessException;
import com.web.common.utils.BeanFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @Author wangzhipeng
 * @Date 2020-08-31 9:49 上午
 * @Description
 */
@WebServlet(urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    private UserDao userDao = (UserDao) BeanFactory.getBean(BeanFactory.USER_DAO);
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String uphone = request.getParameter("phone");
        String upassword = request.getParameter("password");
        User user= null;
        try {
             user = userDao.loginByPhone(uphone, upassword);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter= response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<Object, Object> map = new HashMap<>();
        if (user == null){
            map.put("msg","0");
            map.put("data",null);

            String s = objectMapper.writeValueAsString(map);
            System.out.println(s+"无此用户");
            printWriter.println(s);
        }else {
            map.put("msg","1");
            map.put("data",user);
            String s = objectMapper.writeValueAsString(map);
            System.out.println("登录的用户信息为"+s);
            printWriter.println(s);
        }
        printWriter.flush();
        printWriter.close();

    }
}
